<?php
namespace passport;

use passport\IOauthLogin;
use nekoing\Http;
use passport\ExtendAccessToken;
use passport\ExtendOauthException;
use app\home\model\AccessToken;

class QQOauthLogin implements IOauthLogin
{

    protected $config;

    const API_AUTHORIZE = 'https://graph.qq.com/oauth2.0/authorize';

    const API_TOKEN = 'https://graph.qq.com/oauth2.0/token';

    const API_USERINFO = 'https://api.weibo.com/oauth2/get_token_info';

    public function platform()
    {
        return 'qq';
    }

    public function loadConfig($config)
    {
        $this->config = [
            'appid' => $config['appid'],
            'secret' => $config['secret'],
            'redirect_uri' => $config['redirect_uri']
        ];
    }

    public function authorize($scope, $state = '')
    {
        $params = [
            'response_type' => 'code',
            'client_id' => $this->config['appid'],
            'redirect_uri' => $this->config['redirect_uri'],
            'state' => $state,
            'scope' => $this->scopeTransform($scope)
        ];
        
        $url = self::API_AUTHORIZE . '?' . http_build_query($params);
        header('Location: ' . $url);
        exit();
    }

    public function parseAuthorizeCode()
    {
        return input('code');
    }

    public function refresh($refreshToken)
    {}

    public function scopeTransform($scope)
    {
        $scopeMap = [
            AccessToken::SCOPE_BASIC => 'get_user_info'
        ];
        
        $scopeItems = explode(',', $scope);
        $scope = [];
        foreach ($scopeItems as $item) {
            if (isset($scopeMap[$item])) {
                $scope[] = $scopeMap[$item];
            }
        }
        
        return join(',', array_unique($scope));
    }

    public function token($code)
    {
        $params = [
            'grant_type' => 'authorization_code',
            'client_id' => $this->config['appid'],
            'client_secret' => $this->config['secret'],
            'code' => $code,
            'redirect_uri' => $this->config['redirect_uri']
        ];
        
        $url = self::API_TOKEN . '?' . http_build_query($params);
        
        $res = Http::call($url, null, true);
        parse_str($res, $res);
        if (! empty($res['access_token'])) {
            $token = new ExtendAccessToken();
            $token->data = $res;
            $token->platform = $this->platform();
            $token->token = $res['access_token'];
            $token->expire = $res['expires_in'];
            $token->appid = $this->config['appid'];
            
            return $token;
        } else {
            throw new ExtendOauthException($res['msg'], $res['code']);
        }
    }

    public function openid($token)
    {
        return $token->uid;
    }

    public function userinfo($token)
    {
        
    }
}